﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AvalonDock.Layout;
using Microsoft.Practices.Prism.Regions;

namespace JXPlatform.Infrastructure.RegionAdapters
{
    [Export]
    public class LayoutDocumentPaneRegionAdapter : RegionAdapterBase<LayoutDocumentPane>
    {
        private LayoutDocumentPane _regionTarget;
        private IRegion _region;

        [ImportingConstructor]
        public LayoutDocumentPaneRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory) 
            : base(regionBehaviorFactory)
        {
        }

        protected override void Adapt(IRegion region, LayoutDocumentPane regionTarget)
        {
            if (regionTarget == null)
            {
                throw new ArgumentNullException("regionTarget");
            }

            if (regionTarget.ChildrenCount != 0)
            {
                throw new InvalidOperationException();
            }

            _regionTarget = regionTarget;
            _regionTarget.Children.CollectionChanged += ChildrenOnCollectionChanged;

            _region = region;
            region.Views.CollectionChanged += ViewsOnCollectionChanged;
            region.ActiveViews.CollectionChanged += ActiveViewsOnCollectionChanged;
        }

        private void ActiveViewsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                var view = e.NewItems[0];
                var layoutDocument = _regionTarget.Children.FirstOrDefault(r => r.Content == view);
                if (layoutDocument == null)
                {
                    return;
                }

                layoutDocument.IsActive = true;
            }
        }

        private void ChildrenOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                var layoutDocument = e.OldItems[0] as LayoutDocument;
                if (layoutDocument != null)
                {
                    _region.Remove(layoutDocument.Content);
                }
            }
        }

        protected override IRegion CreateRegion()
        {
            return new SingleActiveRegion();
        }

        private void ViewsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                var view = e.NewItems[0];
                var layoutDocument = new LayoutDocument() { Content = view, Title = view.ToString() };
                _regionTarget.Children.Add(layoutDocument);
                _region.Activate(view);
            }
        }
    }
}
